//定义全局方法。
const cp = {};
var flyEvent;
cp.viewer = null;
cp.viewerDe = null;
cp.labelProvider = null;
cp.imgProvider = null;
cp.geojsonData = {};
cp.currentEntity = null;
cp.currentPolygon = null;
cp.currentPolygonHeight = null;
cp.currentPolygonColor = null;
cp.isOnline = true;
cp.tilsPi = [];
cp.outLineIcenter = "http://219.143.189.234:6633";
cp.inLineIcenter =  "http://192.168.4.120:8310"
//三维球初始化
cp.cesiumInit = function () {
    //使用cesium ion时需要使用key
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiOWI5YjljNy1jMWY0LTRkNTgtYjJkNy05NWMzZmZjYmVhNGMiLCJpZCI6NjE4Niwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTU0NTU1OTc1M30.y-BfaFk5W2Kpvdb6k21p42t52qRupO3wexT8Qasz3iI';
    cp.viewer = new Cesium.Viewer('cesiumContainer', {
        //shouldAnimate: true,
        //animation: true,]
        infoBox:false,
        selectionIndicator: false,
        geocoder:false,
        homeButton:false,
        sceneModePicker:false,
        baseLayerPicker:false,
        navigationHelpButton:false,
        animation:false,
        timeline:false,
        fullscreenButton:false,
        vrButton:false
    });
    window.viewer = cp.viewer;
    viewer._cesiumWidget._creditContainer.style.display="none";  
    
    //viewer.scene._terrainExaggeration = 2;
    let defaultKey='19b72f6cde5c8b49cf21ea2bb4c5b21e';
    if(cp.isOnline){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0));//可以先清除默认的第一个影像 bing地图影像。 当然不作处理也行
        var imgUrl="http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles"+"&tk=" + defaultKey;
       
        //cp.imgProvider = viewer.imageryLayers.addImageryProvider(
            // new Cesium.UrlTemplateImageryProvider({
            //     url: "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali",
            //     baseLayerPicker: false
            // })
            // new Cesium.WebMapTileServiceImageryProvider({
            //     url: imgUrl,
            //     layer: "tdtBasicLayer",
            //     style: "default",
            //     format: "image/jpeg",
            //     maximumLevel:18, //天地图的最大缩放级别
            //     tileMatrixSetID: "GoogleMapsCompatible",
            //     show: false
            // })
        //);
        // var labelUrl="http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg"+"&tk="+'19b72f6cde5c8b49cf21ea2bb4c5b21e';
        // cp.labelProvider = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
        //     url:labelUrl,
        //     layer: "tdtAnnoLayer",
        //     style: "default",
        //     maximumLevel:18,//天地图的最大缩放级别
        //     format: "image/jpeg",
        //     tileMatrixSetID: "GoogleMapsCompatible",
        //     show: false
        // }));
        
    }else{
        viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
            url: `http://10.100.3.55:8310/tilecache/service/wms`,
            layers: 'Global_Image_HBJ-JPEG-4326',
            parameters: {
                format: 'image/JPEG'
            },
            srs: 'EPSG:4326'
        }));
        // viewer.terrainProvider=new Cesium.CesiumTerrainProvider({
        //     url: `http://10.100.3.55:8310/tilecache/service/terrain/Global_DEM_HBJ-TERRAIN-4326`
        // })
    }
    viewer.scene.sun.show = false; //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
    viewer.scene.moon.show = false;
    viewer.scene.skyBox.show = false;//关闭天空盒，否则会显示天空颜色
    
    viewer.scene.undergroundMode = true; //重要，开启地下模式，设置基色透明，这样就看不见黑色地球了
    //viewer.scene.underGlobe.show = true;
    //viewer.scene.underGlobe.baseColor = new Cesium.Color(0, 0, 0, 0);
    //viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
    viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
    viewer.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);
    viewer.scene.skyAtmosphere.show=false;//关闭大气层
    viewer.scene.globe.showGroundAtmosphere = false;//关闭大气渲染

    const leftClickHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
    leftClickHandler.setInputAction(function (movement) {
        const pickedObject = viewer.scene.pick(movement.position)
        
        if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.leftClick === 'function') {
            pickedObject.id.leftClick(pickedObject.id)
        } else {
            const oneDiv = window.document.getElementById("eq_detail")
            oneDiv.style.display = 'none'
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
cp.addBillboard = function (id, info ,position, img, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        info:info,
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1],position[2] ),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            // width: 20,//36,91
            // height: 20,
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        cursor: true
    })
    //simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
cp.addBillboardTwinkle = function (id,info, position, img, type, event) {
    
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        info:info,
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1],position[2] ),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            width:36,
            color :new Cesium.CallbackProperty(function () {
                if(flog){
                    x=x-0.005;
                    if(x<=0){
                        flog=false;
                    }
                }else{
                    x=x+0.005;
                    if(x>=1){
                        flog=true;
                    }
                }
                return Cesium.Color.RED.withAlpha(x);
            },false),
            // height: 91,
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        cursor: true
    })
    //simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},

cp.addTiles = function(url , matrix){
    viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        url : url,
        modelMatrix	: matrix
    }))    
}
cp.addPolygon = function(id,arr,color){
    let simplePointEntity =cp.viewer.entities.add({
        id: id,
        polygon: {
            //hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
            hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights(arr),
            material: Cesium.Color.fromCssColorString(color).withAlpha(.3),
            height : 13.6
            
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
    });
    // let cartographics = [];
    // let tile = [[
    //     [118.768889,32.072568],
    //     [118.769164,32.072373],
    //     [118.769065,32.072269],
    //     [118.769146,32.072208],
    //     [118.769070,32.072132],
    //     [118.768813,32.072308],
    //     [118.768797,32.072396]
    // ],
    // [
    //     [118.769311,32.072826],
    //     [118.769336,32.072810],
    //     [118.769353,32.072827],
    //     [118.769318,32.072853],
    //     [118.769304,32.072860],
    //     [118.769234,32.072881],
    //     [118.769171,32.072876],
    //     [118.769119,32.072859],
    //     [118.769075,32.072828],
    //     [118.769111,32.072855],
    //     [118.769075,32.072827],
    //     [118.769050,32.072798],
    //     [118.769030,32.072756],
    //     [118.769010,32.072723],
    //     [118.768996,32.072691],
    //     [118.768976,32.072654],
    //     [118.769031,32.072615],
    //     [118.769069,32.072589],
    //     [118.769100,32.072621],
    //     [118.769157,32.072679],
    //     [118.769213,32.072735],
    //     [118.769246,32.072716]
    // ]]

    // let drawPolygon = function(cartographics,a) {
    //     var ddd = new Cesium.GeometryInstance({
    //         geometry: new Cesium.PolygonGeometry({
    //             polygonHierarchy : new Cesium.PolygonHierarchy(cartographics)
    //         }),
    //         id:'B'+(a+1) ,
    //         attributes: {
    //             color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(0.85, 0.85, 0, 1))
    //         }
    //     })

    //     return cp.viewer.scene.primitives.add(new Cesium.GroundPrimitive({
    //         geometryInstances: ddd,
    //         classificationType: Cesium.ClassificationType.BOTH,
    //     }));
    // }
    // for(let i = 0; i<tile.length;i++){
    //     for (var m in tile[i]) {
    //         let lonh = tile[i][m][0];
    //         let lath = tile[i][m][1];
    //         if(lath !== undefined){
    //             var position = Cesium.Cartesian3.fromDegrees(parseFloat(lonh), parseFloat(lath));
    //             cartographics.push(position);
    //         }
    //     }
    //     cp.tilsPi.push(drawPolygon(cartographics,i));
    //     cartographics = [];
    // }
}
cp.tilsPiDestory = function(){
    if(cp.tilsPi && cp.tilsPi.length>0){
        for(const item of cp.tilsPi){
            cp.viewer.scene.primitives.remove(item)
        }
    }
}
//相机飞行
cp.flyTo = function (x, y, h, heading, pitch, roll) {
    cp.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, h), // 设置位置
        orientation: {
            heading: heading, // 方向
            pitch: pitch, // 倾斜角度
            roll: roll
        },
    });
}
//获取中心点
cp.getCenter = function () {
    let centerx = (viewer.camera.positionCartographic.longitude * 180) / Math.PI
    let centery = (viewer.camera.positionCartographic.latitude * 180) / Math.PI
    let height = Math.ceil(viewer.camera.positionCartographic.height)
    let heading = viewer.camera.heading
    let pitch = viewer.camera.pitch
    let roll = viewer.camera.roll
    return centerx + ',' + centery + ',' + height + ',' + heading + ',' + pitch + ',' + roll
},







// 复位功能
cp.reset = function () {
    cp.viewer.camera.flyHome()
}
//************************************************** */
//显示或隐藏地形 
cp.showGaocheng = function (isShow) {
    if (isShow) {
        var urlon = "https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path";
        cp.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
            url: urlon,
            requestVertexNormals: true,
            requestWaterMask: true //水波纹
        });
    } else {
        cp.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({
            ellipsoid: Cesium.Ellipsoid.WGS84,
        });
    }
}
cp.option=function(x, y, h, heading, pitch, roll,timer=5) {
    return {
        destination: Cesium.Cartesian3.fromDegrees(x, y, h),
        orientation: {
            heading,
            pitch,
            roll
        },
        duration: timer,
    }
}
cp.initCesiumView=function(x, y, h, heading, pitch, roll) {
    //银河系
    viewer.scene.camera.setView({
        // 初始化相机经纬度
        destination: new Cesium.Cartesian3.fromDegrees(x, y, h),
        orientation: {
            heading,
            pitch, //从上往下看为-90
            roll
        }
    })
}



//统一导出该模块，包含方法和所需变量
export default cp;